package cn.wikiflyer.beikang.act;

import java.lang.reflect.Type;

import net.tsz.afinal.annotation.view.ViewInject;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import cn.wikiflyer.beikang.BaseActivity;
import cn.wikiflyer.beikang.IApplication;
import cn.wikiflyer.beikang.R;
import cn.wikiflyer.beikang.act.cart.bean.BKCartListBean;
import cn.wikiflyer.beikang.act.cart.bean.BKCartListBean.BKCartBean;
import cn.wikiflyer.beikang.act.cart.OrderInfoAct;
import cn.wikiflyer.beikang.act.product.ProductInfoAct;
import cn.wikiflyer.beikang.act.user.setting.UserSettingLoginAct;
import cn.wikiflyer.beikang.bean.base.BKBaseBean;
import cn.wikiflyer.beikang.view.AddAndSubView;
import cn.wikiflyer.beikang.view.AddAndSubView.ICartUpdate;
import cn.wk.libs4a.WKApplication;
import cn.wk.libs4a.net.WKAsyncTaskPro;
import cn.wk.libs4a.view.list.WKListViewInterface;
import cn.wk.libs4a.view.list.WKListViewUtils;
import cn.wk.libs4a.view.list.WKViewHolder;
import cn.wk.libs4a.view.pulltorefresh.PullToRefreshBase.Mode;
import cn.wk.libs4a.view.pulltorefresh.PullToRefreshListView;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

public class CopyOfCartAct extends BaseActivity implements WKListViewInterface {

	private WKListViewUtils<BKCartBean, BKCartListBean> listViewUtils;
	private View footView;

	private TextView foot;

	private TextView price;

	private TextView btn_submit;

	@ViewInject(id = R.id.no_product)
	private View no_product;

	@ViewInject(id = R.id.list)
	private View list;

	private void showClear() {
		list.setVisibility(View.GONE);
		no_product.setVisibility(View.VISIBLE);
	}

	private void hideClear() {
		list.setVisibility(View.VISIBLE);
		no_product.setVisibility(View.GONE);
	}

	@ViewInject(id = R.id.btn_go, click = "onClick")
	private View btn_go;

	public void onClick(View view) {
		if (view.getId() == R.id.btn_go) {
			TabAct.self.setTab(2);
		}
	}

	@Override
	public void loadXml() {
		setContentView(R.layout.bk_act_shop);
	}

	@Override
	public void init() {
		footView = LayoutInflater.from(ctx).inflate(R.layout.cart_bottom_lay,
				null);
		foot = (TextView) footView.findViewById(R.id.foot);
		price = (TextView) footView.findViewById(R.id.price);
		btn_submit = (TextView) footView.findViewById(R.id.btn_submit);

		PullToRefreshListView pList = (PullToRefreshListView) findViewById(R.id.wk_pull_refresh_list);
		listViewUtils = new WKListViewUtils<BKCartBean, BKCartListBean>() {
		};
		listViewUtils.init(ctx, this, pList);
		listViewUtils.listView.addFooterView(footView);
		pList.setMode(Mode.DISABLED);

		footView.findViewById(R.id.btn_submit).setOnClickListener(
				new OnClickListener() {
					public void onClick(View arg0) {
						Intent orderIntent = new Intent(ctx, OrderInfoAct.class);
						orderIntent.putExtra("basebean", listViewUtils.bean);
						startActivity(orderIntent);
					}
				});

	}

	@Override
	public void setData() {
	}

	@Override
	protected void onRestart() {
		super.onRestart();
	}

	@Override
	protected void onResume() {
		super.onResume();
		if (app().getLoginSession() == null) {
			showClear();
			IApplication.showToast("未登录");
		} else {
			listViewUtils.updateData();
		}
	}

	@Override
	public String getData(boolean... isLocal) {
		return app().net.getShopList(listViewUtils.page,
				listViewUtils.pageCount, isLocal);
	}

	@Override
	public void getDataBack(String result, boolean isLocal) {
		Type cvbType = new TypeToken<BKBaseBean<BKCartListBean>>() {
		}.getType();
		Gson gson = new Gson();
		BKBaseBean<BKCartListBean> base = gson.fromJson(result, cvbType);
		if (base.status == 1) {
			listViewUtils.bean = base;
			listViewUtils.list.addAll(base.data.list);
			// 更新下数据
			for (int i = 0; i < listViewUtils.list.size(); i++) {
				listViewUtils.list.get(i).countLocal = Integer
						.valueOf(listViewUtils.list.get(i).quantity);
			}
			// 更新下数据
			updatUI();

			listViewUtils.adapter.notifyDataSetChanged();
		} else {
			WKApplication.showMsg("是否登录?", "是",
					new DialogInterface.OnClickListener() {
						public void onClick(DialogInterface dialog, int which) {
							startActivity(new Intent(ctx,
									UserSettingLoginAct.class));
						}
					}, "否", null);
		}
	}

	@Override
	public WKViewHolder createViewHolder(View arg1) {
		return new MyHolder(arg1);
	}

	@Override
	public int getItemViewId() {
		return R.layout.item_cart;
	}

	/**
	 * 自定义的Item的Holder
	 */
	class MyHolder extends WKViewHolder<BKCartBean> {
		private View itemView;
		private ImageView img_logo;
		private TextView tv_name;
		private TextView tv_price;
		private AddAndSubView asView;

		public MyHolder(View arg0) {
			this.itemView = arg0;
			img_logo = (ImageView) itemView.findViewById(R.id.imageView1);
			tv_name = (TextView) itemView.findViewById(R.id.textView_name);
			tv_price = (TextView) itemView.findViewById(R.id.textView_price);
			asView = (AddAndSubView) itemView.findViewById(R.id.addandsubView);
			asView.setCartUpdate(new ICartUpdate() {
				@Override
				public void updateCart(String id, int num) {
					for (int i = 0; i < listViewUtils.list.size(); i++) {
						if (listViewUtils.list.get(i).id.equals(id)) {
							if (listViewUtils.list.get(i).countLocal != num) {
								listViewUtils.list.get(i).countLocal = num;
								new UpdateOrderNumTask(ctx, asView,
										listViewUtils.list.get(i).quantity,
										num, id);
							}
							break;
						}
					}
					updatUI();
				}
			});
		}

		@Override
		public void setData(final BKCartBean t) {
			app().imageLoader.displayImage(t.thumb, img_logo);
			asView.setId(t.id);
			img_logo.setOnClickListener(new OnClickListener() {
				public void onClick(View arg0) {
					Intent i = new Intent(ctx, ProductInfoAct.class);
					i.putExtra("id", t.id);
					startActivity(i);
				}
			});
			tv_name.setText("" + t.title);
			tv_price.setText("¥" + t.unit_price);
			asView.setNum(Integer.valueOf(t.quantity));
		}
	}

	@Override
	protected void onPause() {
		super.onPause();
	}

	private void updatUI() {
		int count = 0;
		int cost = 0;
		for (int i = 0; i < listViewUtils.list.size(); i++) {
			int c = listViewUtils.list.get(i).countLocal;
			int m = Integer.valueOf(listViewUtils.list.get(i).unit_price);
			count += c;
			cost += (c * m);
		}
		if (count == 0 && IApplication.isBackWhen0) {
			showClear();
			foot.setText("您的购物车还是空的，赶紧行动吧！");
			btn_submit.setVisibility(View.INVISIBLE);
		} else {
			hideClear();
			foot.setText("您当前已经选择了" + count + " 盒");
			btn_submit.setVisibility(View.VISIBLE);
		}
		price.setText("¥" + cost);
	}

	/**
	 * 更新购物车内商品数量
	 */
	class UpdateOrderNumTask extends WKAsyncTaskPro {
		private AddAndSubView mAddAndSubView;
		private int oldNum;
		private int newNum;
		private String cartid;

		public UpdateOrderNumTask(Context context, AddAndSubView aasView,
				int oldNum, int newNum, String cartid) {
			super(context);
			this.mAddAndSubView = aasView;
			this.oldNum = oldNum;
			this.newNum = newNum;
			this.cartid = cartid;
		}

		@Override
		protected String doInBackground(boolean... params) {
			return app().net.updateOrderNum("" + cartid, "" + newNum);
		}

		@Override
		protected void doOnPostExecute(String result, boolean isLocal) {
			Type cvbType = new TypeToken<BKBaseBean>() {
			}.getType();
			Gson gson = new Gson();
			BKBaseBean mBKBaseBean = gson.fromJson(result, cvbType);
			if (mBKBaseBean.status == 1) {
				// Toast.makeText(ctx, "更新成功", 0).show();
				mAddAndSubView.setNum(newNum);
			} else {
				Toast.makeText(ctx, "更新失败", 0).show();
				mAddAndSubView.setNum(oldNum);
			}
		}
	}
}
